package com.zxp.pstationapk.view;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.qmuiteam.qmui.widget.QMUIProgressBar;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.zxp.pstationapk.R;
import com.zxp.pstationapk.base.Constant;
import com.zxp.pstationapk.fastjson.FastJsonConverterFactory;
import com.zxp.pstationapk.retrofit.ApiService;
import com.zxp.pstationapk.retrofit.ProgressHandler;
import com.zxp.pstationapk.retrofit.ProgressHelper;
import com.zxp.pstationapk.util.CheckFileisExitTool;
import com.zxp.pstationapk.util.ToastTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author Created by zxp on 2018/5/22.
 *         加载高清大图activity,拒绝压缩后显示失真效果
 */

public class LargeImageViewActivity extends AppCompatActivity {
    @BindView(R.id.imageView)
    SubsamplingScaleImageView imageView;
    @BindView(R.id.topbar_large_image)
    QMUITopBar topbar_large_image;
    @BindView(R.id.progress_bar)
    QMUIProgressBar progress_bar;
    private String local_png_url = null;
    private String pdf_load_url_content = null;
    private static final String TAG = LargeImageViewActivity.class.getSimpleName();
    private ImageSource uri;
    private Dialog mDownloadDialog;

    private NumberProgressBar numberProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_large_image_view);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        //获取参数，初始化标题栏
        Intent intent = getIntent();
        pdf_load_url_content = intent.getStringExtra("stationName");
        topbar_large_image.setTitle(pdf_load_url_content);

        checkFileExit();

        topbar_large_image.addRightImageButton(R.drawable.ic_file_download_black_24dp, R.id.topbar_right_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUpDownLoadDialog();
            }
        });
    }

    private void checkFileExit() {
        //显示图片
        local_png_url = "///" + "storage/emulated/0/" + pdf_load_url_content + ".jpg";
        /**
         * 判断本地是否存在此文件
         */
        if (CheckFileisExitTool.check(local_png_url)) {
            uri = ImageSource.uri(local_png_url);
            setView(uri);
        } else {
            ToastTool.show("此文件尚未下载，不可查看！");
        }
    }

    /**
     * 显示下载进度
     */
    private void setUpDownLoadDialog() {
        ToastTool.show("图纸正在下载中");
        String downloadUrl = pdf_load_url_content + Constant.pdf_load_url_end_jpg;
        downLoadPng(downloadUrl);
        mDownloadDialog = new Dialog(this, R.style.Theme_AppCompat_Dialog_Alert);
        View view = getLayoutInflater().inflate(R.layout.progress_dialog, null);
        numberProgressBar = (NumberProgressBar)view.findViewById(R.id.number_progress_bar);
        mDownloadDialog.setContentView(view);
        mDownloadDialog.show();
    }

    //下载
    private void downLoadPng(String downloadUrl) {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().addConverterFactory(FastJsonConverterFactory.create()).baseUrl(Constant.baseUrl);
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
        ApiService retrofit = retrofitBuilder.client(builder.build()).build().create(ApiService.class);
        ProgressHelper.setProgressHandler(new ProgressHandler() {
            @Override
            protected void onProgress(long progress, long total, long speed, boolean done) {
                numberProgressBar.setProgress((int) (progress/1024));
            }
        });

        Call<ResponseBody> call = retrofit.downLoadImage(downloadUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    saveImageFile(response.body(), pdf_load_url_content);
                    if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
                        mDownloadDialog.dismiss();
                    }
                    ToastTool.show("图纸下载完成");
                    checkFileExit();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    private void setView(ImageSource uri) {
        imageView.setImage(uri);
    }

    //保存图片
    private void saveImageFile(ResponseBody body, String s) {
        try {
            File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, s + ".jpg");
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();
            } catch (IOException e) {
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
        }
    }
}
